import { log } from 'cetools'
import { IRenderMessage, IRenderReplyMessage, messageMagic } from '../../../declare/Message'
import { EventType } from '../../../declare/EventType'
const ipc = window.electron.ipcRenderer

const TIME_OUT = 600000

export type Callback = (params?: unknown) => void
export interface ITimedCallback {
    timeOut?: number
    callback?: Callback
}

interface MsgItem {
    sendTime: number
    messageId: string
    callback: Callback
}

const messageQueue: Array<MsgItem> = []

ipc.on(messageMagic, (event, data) => {
    log.info('ipcOn:', event, data)
    const result = JSON.parse(data) as IRenderReplyMessage
    if (result.isSuccess) {
        log.info('result', result, messageQueue)
        const found = messageQueue.find((value) => {
            return value.messageId === result.messageId
        })
        log.info('found', found)
        if (found && found.callback) {
            found.callback(result.data)
        }
    }
})

// const timer = setInterval(() => {
//     messageQueue.forEach((value) => {
//         Atomics.exchange()
//         if (Date.now() - value > TIME_OUT) {
//             /* empty */
//         }
//     })
// }, 500)

export const cleanup = () => {
    clearInterval(timer)
}

let messageCounter = 0

const IPCSend = (data: IRenderMessage<T>, callback?: Callback) => {
    messageCounter++
    data.messageId = messageCounter.toString()
    if (callback) {
        messageQueue.push({ messageId: data.messageId, callback: callback, sendTime: Date.now() })
    }
    ipc.send(messageMagic, JSON.stringify(data))
}

/**
 * Choose directory
 */
export const selectDirectory = (callback?: Callback) => {
    IPCSend({ eventType: EventType.SELECT_DIRECTORY }, callback)
}

/**
 * Write text content to file
 * @param data text content
 * @param callback completion callback
 */
export const writeTextFile = (data: IWiteTextFile, callback?: Callback) => {
    IPCSend({ eventType: EventType.WRITE_TEXT_FILE, data: data }, callback)
}

export default ipc
